﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System.Threading.Tasks;
using Volo.Abp;
using Xms.Abp.AspNetCore.Mvc;

namespace AccountManagement;

[RemoteService(Name = AccountRemoteServiceConsts.RemoteServiceName)]
[Area(AccountRemoteServiceConsts.ModuleName)]
[ControllerName("Account")]
[Route("api/management/account")]
[SwaggerTag("个人账户")]
public class AccountController : XmsController<IAccountService>, IAccountService
{
    [Authorize]
    [HttpPut]
    [Route("profile/password/change")]
    [SwaggerOperation("修改密码")]
    public async Task ChangePwdAsync(ChangePwdParameter parameter)
        => await CurrentService.ChangePwdAsync(parameter);

    [HttpGet]
    [Route("profile")]
    [SwaggerOperation("获取个人资料")]
    public async Task<ProfileResult> GetProfileAsync()
    {
        if (!HttpContext.Request.Cookies.ContainsKey("__tenant") && CurrentUser.TenantId.HasValue && (!CurrentTenant.IsAvailable || !CurrentTenant.Id.HasValue))
        {
            using (CurrentTenant.Change(CurrentUser.TenantId))
            {
                var result = await CurrentService.GetProfileAsync();
                HttpContext.Response.Cookies.Append("__tenant", CurrentUser.TenantId.Value.ToString());
                return result;
            }
        }
        else if (HttpContext.Request.Cookies.ContainsKey("__tenant") && !CurrentUser.TenantId.HasValue)
        {
            using (CurrentTenant.Change(null))
            {
                var result = await CurrentService.GetProfileAsync();
                HttpContext.Response.Cookies.Delete("__tenant");
                return result;
            }
        }
        else
        {
            var result = await CurrentService.GetProfileAsync();
            return result;
        }
    }

    [HttpPost]
    [Route("login")]
    [SwaggerOperation("登录")]
    public async Task<bool> LoginAsync(LoginParameter parameter)
    {
        using (CurrentTenant.Change(parameter.TenantId))
        {
            var result = await CurrentService.LoginAsync(parameter);
            if (result && parameter.TenantId.HasValue)
            {
                HttpContext.Response.Cookies.Append("__tenant", parameter.TenantId.Value.ToString());
            }
            else
            {
                HttpContext.Response.Cookies.Delete("__tenant");
            }
            return result;
        }
    }

    [HttpGet]
    [Route("logout")]
    [SwaggerOperation("退出登录")]
    public async Task LogoutAsync()
    {
        await CurrentService.LogoutAsync();
        if (HttpContext.Request.Cookies.ContainsKey("__tenant"))
        {
            HttpContext.Response.Cookies.Delete("__tenant");
        }
    }

    [Authorize]
    [HttpPut]
    [Route("profile/update")]
    [SwaggerOperation("修改个人资料")]
    public async Task UpdateProfileAsync(UpdateProfileParameter parameter)
        => await CurrentService.UpdateProfileAsync(parameter);
}
